﻿namespace Sai.Core.Reporting
{
	using System;
	using System.IO;

	public class FileBasedReportTransformation : IReportTransformation
	{
        private string _stylesheetContent = string.Empty;
        private ITextTransformer _transformer;

		public FileBasedReportTransformation(string stylesheetPath)
		{
            this.StyleSheetPath = stylesheetPath;
		}

        private string StyleSheetPath { get; set; }

        private string StyleSheetContent
        {
            get
            {
                if (string.IsNullOrEmpty(this._stylesheetContent))
                {
                    if (File.Exists(this.StyleSheetPath))
                    {
                        using (TextReader reader = new StreamReader(this.StyleSheetPath))
                        {
                            this._stylesheetContent = reader.ReadToEnd();
                        }
                    }
                }

                return this._stylesheetContent;
            }
        }

        private ITextTransformer Transformer
        {
            get
            {
                if (this._transformer == null)
                {
                    this._transformer = new XmlTransformer(this.StyleSheetContent);
                }

                return this._transformer;
            }
        }

        public string Transform(IFlattenToXml flattenable)
        {
            return this.Transformer.Transform(flattenable.ToXml());
        }
	}
}
